package com.woniuxy.movie.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.movie.user.dao.UserAccountMapper;
import com.woniuxy.movie.user.dto.AccountDto;
import com.woniuxy.movie.user.exception.UserException;
import com.woniuxy.movie.user.form.PassLoginForm;
import com.woniuxy.movie.user.form.RegisterAccountForm;
import com.woniuxy.movie.user.model.UserAccount;
import com.woniuxy.movie.user.service.UserAccountService;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XIAO
 * @since 2023年10月10日
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public AccountDto register(RegisterAccountForm form) throws Exception {
        //判断用户名手机号是否被注册
        UserAccount name = getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getAccountName, form.getAccountName()));
        if (name != null) throw new UserException(1001, "用户名已被注册");
        UserAccount phone = getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getAccountPhone, form.getAccountPhone()));
        if (phone != null) throw new UserException(1001, "手机号已被注册");
        //注册
        UserAccount account = BeanUtil.toBean(form, UserAccount.class);
        account.setAccountState(1);
        account.setAccountTime(DateUtil.format(new Date(System.currentTimeMillis()),"yyyy-MM-dd HH:mm:ss"));
        save(account);
        return BeanUtil.toBean(account, AccountDto.class);
    }

    @Override
    public AccountDto passLogin(PassLoginForm form) {
        LambdaQueryWrapper<UserAccount> query = new LambdaQueryWrapper<>();
        query.eq(UserAccount::getAccountName, form.getNameOrPhone());
        query.or().eq(UserAccount::getAccountPhone, form.getNameOrPhone());
        List<UserAccount> accounts = list(query);
        if (accounts == null || accounts.size() == 0) throw new UserException(1001, "账号未注册");
        UserAccount userAccount = null;
        for (UserAccount account : accounts) {
            if (!account.getAccountPass().equals(form.getPass())) throw new UserException(1001, "密码错误");
            userAccount = account;
        }
        return BeanUtil.toBean(userAccount, AccountDto.class);
    }
}
